package com.game.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Debug.MemoryInfo;


/**
* @author oven:
* @version 创建时间：2012-11-27 下午4:59:25
* 
*/
public class SystemInfoUtil {
	public static SystemInfoUtil instance =null;
	
	private Context mContext;
	
	private SystemInfoUtil(Activity activity){
		mContext=activity.getApplicationContext();
	}
	
	public static SystemInfoUtil newInstance(Activity activity){
		instance = new SystemInfoUtil(activity);
		return instance;
	}
	
	/**
	 * 获取当前进程占用内存状况
	 * @return
	 */
	public String getCurrentAPPMemoryUsage(){
		ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);   
		int pid = android.os.Process.myPid();
		MemoryInfo[] memoryInfoArray = am.getProcessMemoryInfo(new int[]{pid}); 
		MemoryInfo pidMemoryInfo=memoryInfoArray[0];
		// 获取进程占内存用信息 kb单位
		int memSize = pidMemoryInfo.dalvikPrivateDirty;
		String sSize=changeSizeUnit(memSize);
		sSize=sSize+" "+changeSizeUnit(pidMemoryInfo.getTotalPrivateDirty());
		sSize=sSize+" "+changeSizeUnit(pidMemoryInfo.getTotalPss());
		sSize=sSize+" "+changeSizeUnit(pidMemoryInfo.getTotalSharedDirty());
		return "占用内存:"+sSize;
	}
	
	/**
	 * 转换成适当的 单位
	 * @param size
	 * @return
	 */
	public String changeSizeUnit(int size){
		String result = "";
		int step = 0;
		while(size/1024>=1){
			result=size%1024+getUnit(step)+result;
			size=size/1024;
			step++;
		}
		result=size+getUnit(step)+result;
		return result;
	}
	
	public String getUnit(int step){
		switch (step) {
		case 0: return "KB";
		case 1: return "MB";
		case 2: return "GB";
		default : return "";
		}
	}
	
	
	public long getAvailMemory() {   
        ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);   
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();   
        am.getMemoryInfo(mi);   
        return mi.availMem;   
    }  
	
	public long getAvailMemoryKB(){
		return getAvailMemory()/1024;
	}
	
	public long getAvailMemoryMB(){
		return getAvailMemoryKB()/1024;
	}
	
}

